package com.maibow.interceptor;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.maibow.entity.admin.Module;
import com.maibow.entity.admin.SysOperator;
import com.maibow.util.CommonConstants;

/**
 * 
 * 脉博网络后台管理系统
 * 包名：com.maibow.interceptor
 * 文件名：LoginHandlerInterceptor.java
 * 作者: 吴比(Wubi)
 * 时间：2015年4月2日-上午9:10:59
 * Copyright@ 2015湖南脉博网络科技有限公司-版权所有
 *
 */
public class LoginHandlerInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // TODO Auto-generated method stub
        String path = request.getServletPath();
        if (path.matches(CommonConstants.NO_INTERCEPTOR_PATH)) {
            return true;
        } else {
            // shiro管理的session
            Subject currentUser = SecurityUtils.getSubject();
            Session session = currentUser.getSession();
            SysOperator operator = (SysOperator) session.getAttribute(CommonConstants.SESSION_OPERATOR);
            if (operator != null) {
                // 判断是否拥有当前点击菜单的权限（内部过滤,防止通过url进入跳过菜单权限）
                /**
                 * 根据点击的菜单的xxx.do去菜单中的URL去匹配，
                 * 当匹配到了此菜单
                 * ，判断是否有此菜单的权限，没有的话跳转到登录页面
                 */
                List<Module> moduleList = (List) session.getAttribute(CommonConstants.SESSION_MODULE_LIST); // 获取菜单列表
                path = path.substring(1, path.length());
                if (moduleList == null && moduleList.size() == 0) {
                    response.sendRedirect(request.getContextPath() + CommonConstants.MAIN_LOGIN);
                    return false;
                }

                for (int i = 0; i < moduleList.size(); i++) {
                    if (moduleList.get(i).getSubmodule() == null || moduleList.get(i).getSubmodule().size() == 0) {
                        // response.sendRedirect(request.getContextPath()
                        // +
                        // CommonConstants.MAIN_LOGIN);
                        // return false;
                        continue;
                    }

                    for (int j = 0; j < moduleList.get(i).getSubmodule().size(); j++) {
                        if (moduleList.get(i).getSubmodule().get(j).getModuleurl().split(".do")[0].equals(path.split(".do")[0])) {
                            return true;
                        }
                    }
                }
                return true;
            } else {
                // 登陆过滤
                response.sendRedirect(request.getContextPath() + CommonConstants.MAIN_LOGIN);
                return false;
            }
        }
    }
}
